#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <errno.h>


/**
 * address to name
 */
int main() {
    int ret;

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(8000);
    inet_pton(AF_INET, "127.0.0.1", &sockaddr.sin_addr);;

    char hostbuf[200];
    char servbuf[200];
    socklen_t hostlen = sizeof(hostbuf);
    socklen_t servlen = sizeof(servbuf);
    int flags;

    flags = NI_DGRAM; // 服务基于数据报而非流 
//    flags = NI_NUMERICHOST | NI_NUMERICSERV;
//    flags = NI_NAMEREQD; // 如果找不到主机名, 作为一个错误对待
    
    ret = getnameinfo((struct sockaddr *)&sockaddr, sizeof(sockaddr), hostbuf, hostlen, servbuf, servlen, flags);

    if (ret != 0) {
        printf("getnameinfo error\n");
        exit(1);
    }
    
    printf("host name: %s\nserv name: %s\n", hostbuf, servbuf);
    return 0;
}


